import axios from 'axios'
export default ({
    namespaced:true,
    state:()=>({
        cart:[]
    }),
    mutations:{
        updataCart(state,cart){
          state.cart=cart
        },
        updataCartState(state,spyload){
            // 根据id找到索引修改状态
           const index= state.cart.findIndex(item=>item.id==spyload.id)
           state.cart[index].goods_state=spyload.value
        },
        updataCartCount(state,spyload){
            // 根据id找到索引修改对应的数量
            const index= state.cart.findIndex(item=>item.id==spyload.id)
            state.cart[index].goods_count=spyload.value
        },//修改所有数据的状态
        updataAllState(state,val){
          state.cart.forEach(item => item.goods_state=val);
        }
    },
    actions:{
       async getCartList(context){
          const res= await axios.get('https://www.escook.cn/api/cart')
          context.commit('updataCart', res.data.list);
        }
    },
    getters:{
        allPrice(state){
          return  state.cart.filter(item=>item.goods_state)
        .reduce((sum,item)=>sum+=item.goods_count*item.goods_price,0)
        },
        box(state){
          return  state.cart.filter(item=>item.goods_state)
        .reduce((sum,item)=>sum+=item.goods_count,0)
        },
   },
   
})